// 数据存储模块
const storage = {
    // 存储数据到本地
    save(key, data) {
        localStorage.setItem(key, JSON.stringify(data));
    },

    // 从本地获取数据
    load(key, defaultValue = null) {
        const data = localStorage.getItem(key);
        return data ? JSON.parse(data) : defaultValue;
    },

    // 存储文件
    saveFile(filename, data) {
        const blob = new Blob([data], { type: 'text/plain' });
        const url = URL.createObjectURL(blob);

        const a = document.createElement('a');
        a.href = url;
        a.download = filename;
        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);
        URL.revokeObjectURL(url);
    },

    // 读取文件
    readFile(file, callback) {
        const reader = new FileReader();
        reader.onload = function (e) {
            callback(e.target.result);
        };
        reader.readAsText(file);
    }
};

// 应用状态
const appState = {
    prizes: storage.load('prizes', []),
    participants: storage.load('participants', []),
    winners: storage.load('winners', {}),
    bgmFiles: storage.load('bgmFiles', {}),
    history: storage.load('history', [])
};

// 音频元素引用
const audioElements = {
    drawSound: document.getElementById('draw-sound'),
    winSound: document.getElementById('win-sound'),
    transitionSound: document.getElementById('transition-sound'),
    bgmPlayer: document.getElementById('bgm-player')
};

// DOM 元素引用
const elements = {
    // 导航元素
    navDraw: document.getElementById('nav-draw'),
    navSettings: document.getElementById('nav-settings'),
    navReset: document.getElementById('nav-reset'),
    drawPage: document.getElementById('draw-page'),
    settingsPage: document.getElementById('settings-page'),

    // 抽奖页面元素
    prizeSelect: document.getElementById('prize-select'),
    currentPrizeName: document.getElementById('current-prize-name'),
    remainingCount: document.getElementById('remaining-count'),
    lotteryResult: document.getElementById('lottery-result'),
    lotteryContainer: document.getElementById('lottery-container'),
    lotteryDecor: document.getElementById('lottery-decor'),
    lotteryParticles: document.getElementById('lottery-particles'),
    drawBtn: document.getElementById('draw-btn'),
    drawAllBtn: document.getElementById('draw-all-btn'),

    // 奖项设置元素
    prizeList: document.getElementById('prize-list'),
    emptyPrizes: document.getElementById('empty-prizes'),
    newPrizeName: document.getElementById('new-prize-name'),
    newPrizeCount: document.getElementById('new-prize-count'),
    addPrizeBtn: document.getElementById('add-prize-btn'),

    // 参与名单元素
    participants: document.getElementById('participants'),
    saveParticipants: document.getElementById('save-participants'),
    importParticipants: document.getElementById('import-participants'),
    clearParticipants: document.getElementById('clear-participants'), // 添加这行以修复清空按钮引用

    // 中奖名单元素
    winnersContainer: document.getElementById('winners-container'),
    exportBtn: document.getElementById('export-btn'),
    emptyWinners: document.getElementById('empty-winners'),

    // 音乐控制元素
    bgmUpload: document.getElementById('bgm-upload'),
    bgmUploadBtn: document.getElementById('bgm-upload-btn'),
    bgmFilename: document.getElementById('bgm-filename'),
    bgmList: document.getElementById('bgm-list'),
    emptyBgm: document.getElementById('empty-bgm'),
    bgmSelect: document.getElementById('bgm-select'),
    bgmTest: document.getElementById('bgm-test'),
    bgmStop: document.getElementById('bgm-stop'),
    bgmPlayer: document.getElementById('bgm-player'),

    // 粒子效果元素
    particlesBg: document.getElementById('particles-bg')
};

let currentPrize = null;
let isDrawing = false;
let drawInterval = null;
let shouldPauseDrawAll = false;
let isDrawingAll = false;
let drawAllTimeout = null;

// 初始化页面
function init() {
    createBackgroundParticles();
    renderPrizeList();
    updatePrizeSelect();
    updateDrawButtons();
    renderWinners();

    // 加载参与名单
    if (appState.participants.length > 0) {
        elements.participants.value = appState.participants.join('\n');
    }

    // 初始化音频资源（添加默认音乐）
    initializeDefaultBGM();

    // 注册事件监听器
    registerEventListeners();

    // 页面加载动画
    setTimeout(() => {
        document.body.classList.add('opacity-100');
        document.body.classList.remove('opacity-0');
    }, 100);
}

// 创建背景粒子
function createBackgroundParticles() {
    elements.particlesBg.innerHTML = '';
    for (let i = 0; i < 50; i++) {
        const particle = document.createElement('div');
        particle.className = 'particle';
        const colors = ['bg-primary/50', 'bg-secondary/50', 'bg-accent/50', 'bg-white/30'];
        const color = colors[Math.floor(Math.random() * colors.length)];
        particle.classList.add(color);
        const size = Math.random() * 5 + 2;
        particle.style.width = `${size}px`;
        particle.style.height = `${size}px`;
        const left = Math.random() * 100;
        const top = Math.random() * 100;
        particle.style.left = `${left}%`;
        particle.style.top = `${top}%`;
        const delay = Math.random() * 5;
        const duration = Math.random() * 10 + 5;
        particle.style.animationDelay = `${delay}s`;
        particle.style.animationDuration = `${duration}s`;
        elements.particlesBg.appendChild(particle);
    }
}

// 创建抽奖区域粒子
function createLotteryParticles() {
    elements.lotteryParticles.innerHTML = '';
    for (let i = 0; i < 30; i++) {
        const particle = document.createElement('div');
        particle.className = 'particle';
        const colors = ['bg-white/30', 'bg-secondary/50', 'bg-accent/50'];
        const color = colors[Math.floor(Math.random() * colors.length)];
        particle.classList.add(color);
        const size = Math.random() * 8 + 2;
        particle.style.width = `${size}px`;
        particle.style.height = `${size}px`;
        const left = Math.random() * 100;
        const top = Math.random() * 100;
        particle.style.left = `${left}%`;
        particle.style.top = `${top}%`;
        const delay = Math.random() * 3;
        const duration = Math.random() * 6 + 4;
        particle.style.animationDelay = `${delay}s`;
        particle.style.animationDuration = `${duration}s`;
        elements.lotteryParticles.appendChild(particle);
    }
}





// 注册事件监听器
function registerEventListeners() {
    // 导航栏切换
    elements.navDraw.addEventListener('click', showDrawPage);
    elements.navSettings.addEventListener('click', showSettingsPage);
    elements.navReset.addEventListener('click', resetDraw);

    // 抽奖页功能
    elements.prizeSelect.addEventListener('change', () => {
        const prizeId = elements.prizeSelect.value;
        selectPrize(prizeId);
    });

    elements.drawBtn.addEventListener('click', toggleDraw);
    elements.drawAllBtn.addEventListener('click', drawAll);

    // 奖项管理
    elements.addPrizeBtn.addEventListener('click', addPrize);

    // 参与名单操作
    elements.saveParticipants.addEventListener('click', saveParticipants);
    elements.importParticipants.addEventListener('click', () => {
        const fileInput = document.createElement('input');
        fileInput.type = 'file';
        fileInput.accept = '.txt';
        fileInput.onchange = (e) => {
            const file = e.target.files[0];
            if (file) {
                storage.readFile(file, (content) => {
                    elements.participants.value = content;
                });
            }
        };
        fileInput.click();
    });

    elements.clearParticipants.addEventListener('click', () => {
        if (confirm('确定要清空参与名单吗？')) {
            elements.participants.value = '';
            appState.participants = [];
            storage.save('participants', appState.participants);
            updateDrawButtons();
        }
    });

    // 音乐控制
    elements.bgmUploadBtn.addEventListener('click', () => elements.bgmUpload.click());
    elements.bgmUpload.addEventListener('change', handleBgmUpload);
    elements.bgmTest.addEventListener('click', testBgm);
    elements.bgmStop.addEventListener('click', stopBgm);
    elements.bgmSelect.addEventListener('change', () => {
        const bgmId = elements.bgmSelect.value;
        if (bgmId) {
            playBgm(appState.bgmFiles[bgmId]);
        } else {
            stopBgm();
        }
    });

    elements.exportBtn.addEventListener('click', exportWinners);

    // 滚动效果
    window.addEventListener('scroll', () => {
        if (window.scrollY > 10) {
            elements.navbar.classList.add('py-2');
            elements.navbar.classList.remove('py-3');
        } else {
            elements.navbar.classList.add('py-3');
            elements.navbar.classList.remove('py-2');
        }
    });
}

// 显示抽奖页面
function showDrawPage() {
    elements.drawPage.classList.remove('hidden');
    elements.settingsPage.classList.add('hidden');
    elements.navDraw.classList.add('bg-gradient-red', 'text-white');
    elements.navDraw.classList.remove('hover:bg-primary/20');
    elements.navSettings.classList.remove('bg-gradient-red', 'text-white');
    elements.navSettings.classList.add('hover:bg-primary/20');

    elements.drawPage.classList.add('animate-scale-in');
    setTimeout(() => {
        elements.drawPage.classList.remove('animate-scale-in');
    }, 500);

    createLotteryParticles();
}

// 显示设置页面
function showSettingsPage() {
    elements.drawPage.classList.add('hidden');
    elements.settingsPage.classList.remove('hidden');
    elements.navDraw.classList.remove('bg-gradient-red', 'text-white');
    elements.navDraw.classList.add('hover:bg-primary/20');
    elements.navSettings.classList.add('bg-gradient-red', 'text-white');
    elements.navSettings.classList.remove('hover:bg-primary/20');

    elements.settingsPage.classList.add('animate-scale-in');
    setTimeout(() => {
        elements.settingsPage.classList.remove('animate-scale-in');
    }, 500);
}

// 重置抽奖
function resetDraw() {
    if (confirm('确定要重置所有抽奖结果吗？')) {
        addHistoryEntry('重置抽奖，结束当前轮次');

        if (Object.keys(appState.winners).length > 0) {
            appState.history.push({
                timestamp: new Date().toISOString(),
                winners: appState.winners
            });
            storage.save('history', appState.history);
        }

        appState.winners = {};
        storage.save('winners', appState.winners);

        renderWinners();
        updateDrawButtons();

        if (isDrawing) {
            toggleDraw();
        }

        elements.lotteryResult.classList.add('scale-up');
        elements.lotteryResult.textContent = '重置完成';
        setTimeout(() => {
            elements.lotteryResult.classList.remove('scale-up');
            elements.lotteryResult.textContent = '???';
        }, 2000);

        alert('抽奖已重置');


        selectPrize(null); // 清除当前选择的奖项
        elements.prizeSelect.value = ''; // 重置下拉框
    }
}

// 添加历史记录
function addHistoryEntry(message) {
    const historyItem = {
        timestamp: new Date().toISOString(),
        message: message
    };
    appState.history.push(historyItem);
    storage.save('history', appState.history);
}

// 选择奖项
function selectPrize(prizeId) {
    if (!prizeId) {
        currentPrize = null;
        elements.currentPrizeName.textContent = '请选择奖项';
        elements.remainingCount.textContent = '0';
        updateDrawButtons();
        elements.lotteryContainer.classList.remove('bg-gradient-red', 'bg-gradient-gold', 'bg-gradient-tech');
        elements.lotteryContainer.classList.add('bg-gradient-red');
        return;
    }

    const prize = appState.prizes.find(p => p.id === prizeId);
    if (prize) {
        currentPrize = prize;
        elements.currentPrizeName.textContent = prize.name;
        const winnersCount = appState.winners[prizeId] ? appState.winners[prizeId].length : 0;
        const remaining = prize.count - winnersCount;
        elements.remainingCount.textContent = remaining;
        updateDrawButtons();

        elements.lotteryContainer.classList.remove('bg-gradient-red', 'bg-gradient-gold', 'bg-gradient-tech');
        if (prizeId === appState.prizes[0]?.id) {
            elements.lotteryContainer.classList.add('bg-gradient-red');
        } else if (prizeId === appState.prizes[1]?.id) {
            elements.lotteryContainer.classList.add('bg-gradient-gold');
        } else {
            elements.lotteryContainer.classList.add('bg-gradient-tech');
        }

        elements.currentPrizeName.classList.add('scale-up');
        setTimeout(() => {
            elements.currentPrizeName.classList.remove('scale-up');
        }, 300);
    }
}









// 开始/停止抽奖
function toggleDraw() {
    if (!currentPrize) {
        alert('请先选择奖项');
        return;
    }

    const winnersCount = appState.winners[currentPrize.id] ? appState.winners[currentPrize.id].length : 0;
    if (winnersCount >= currentPrize.count) {
        alert('该奖项已抽完所有名额');
        return;
    }

    const remainingParticipants = getRemainingParticipants();
    if (remainingParticipants.length === 0) {
        alert('没有可参与抽奖的人员');
        return;
    }

    if (!isDrawing) {
        isDrawing = true;
        elements.drawBtn.innerHTML = '<i class="fa fa-stop mr-2"></i> 停止抽奖';
        elements.drawBtn.classList.remove('bg-gradient-red');
        elements.drawBtn.classList.add('bg-gradient-gold');

        audioElements.drawSound.currentTime = 0;
        audioElements.drawSound.loop = true;
        audioElements.drawSound.play();

        let speed = 50;
        let slowDownInterval;
        let slowDownFactor = 1;

        drawInterval = setInterval(() => {
            const randomIndex = Math.floor(Math.random() * remainingParticipants.length);
            elements.lotteryResult.textContent = remainingParticipants[randomIndex];

            if (slowDownInterval && Math.random() < 0.05 * slowDownFactor) {
                speed += 5;
                clearInterval(drawInterval);
                drawInterval = setInterval(() => {
                    const randomIndex = Math.floor(Math.random() * remainingParticipants.length);
                    elements.lotteryResult.textContent = remainingParticipants[randomIndex];
                }, speed);
                slowDownFactor += 0.1;
            }
        }, speed);

        setTimeout(() => {
            slowDownInterval = setInterval(() => {
                if (speed > 200) {
                    clearInterval(slowDownInterval);
                }
            }, 500);
        }, 3000 + Math.random() * 2000);
    } else {
        clearInterval(drawInterval);
        clearTimeout(drawAllTimeout); // 清除延迟任务
        isDrawing = false;
        shouldPauseDrawAll = true; // 确保标记为暂停

        elements.drawBtn.innerHTML = '<i class="fa fa-play mr-2"></i> 开始抽奖';
        elements.drawBtn.classList.remove('bg-gradient-gold');
        elements.drawBtn.classList.add('bg-gradient-red');

        audioElements.drawSound.pause();
        audioElements.drawSound.currentTime = 0;

        audioElements.winSound.currentTime = 0;
        audioElements.winSound.play();

        const randomIndex = Math.floor(Math.random() * remainingParticipants.length);
        const winner = remainingParticipants[randomIndex];

        if (!appState.winners[currentPrize.id]) {
            appState.winners[currentPrize.id] = [];
        }
        appState.winners[currentPrize.id].push(winner);
        storage.save('winners', appState.winners);

        renderWinners();

        const prizeGroup = document.querySelector(`#winners-list-${currentPrize.id}`).parentElement;
        prizeGroup.classList.add('scale-up');
        setTimeout(() => {
            prizeGroup.classList.remove('scale-up');
        }, 300);

        elements.lotteryResult.textContent = winner;
        elements.lotteryResult.classList.add('scale-up');

        elements.lotteryDecor.classList.remove('opacity-0');
        elements.lotteryDecor.classList.add('opacity-100');
        elements.lotteryContainer.classList.add('lottery-glow');

        setTimeout(() => {
            elements.lotteryResult.classList.remove('scale-up');
            elements.lotteryDecor.classList.add('opacity-0');
            elements.lotteryDecor.classList.remove('opacity-100');
            elements.lotteryContainer.classList.remove('lottery-glow');
        }, 2000);

        selectPrize(currentPrize.id);
        updateDrawButtons();
        addHistoryEntry(`抽中 ${currentPrize.name}: ${winner}`);
    }
}


// 获取剩余抽奖人数
function getRemainingParticipants() {
    const allWinners = [];
    for (const prizeId in appState.winners) {
        allWinners.push(...appState.winners[prizeId]);
    }
    return appState.participants.filter(p => !allWinners.includes(p));
}

// 更新抽奖按钮状态
function updateDrawButtons() {
    const remainingParticipants = getRemainingParticipants();
    const hasParticipants = remainingParticipants.length > 0;

    if (!currentPrize) {
        elements.drawBtn.disabled = true;
        elements.drawAllBtn.disabled = true;
        return;
    }

    const winnersCount = appState.winners[currentPrize.id] ? appState.winners[currentPrize.id].length : 0;
    const hasRemaining = winnersCount < currentPrize.count;

    elements.drawBtn.disabled = !hasParticipants || !hasRemaining;
    elements.drawAllBtn.disabled = !hasParticipants || !hasRemaining;

    // 如果正在执行一键抽奖，则禁用“开始抽奖”
    elements.drawBtn.disabled = isDrawingAll || elements.drawBtn.disabled;
}


/// 一键抽完所有名额
function drawAll() {
    if (!currentPrize) {
        alert('请先选择奖项');
        return;
    }

    const winnersCount = appState.winners[currentPrize.id] ? appState.winners[currentPrize.id].length : 0;
    const remaining = currentPrize.count - winnersCount;

    if (remaining <= 0) {
        alert('该奖项已抽完所有名额');
        return;
    }

    const remainingParticipants = getRemainingParticipants();
    if (remainingParticipants.length === 0) {
        alert('没有可参与抽奖的人员');
        return;
    }

    if (remainingParticipants.length < remaining) {
        if (!confirm(`剩余参与人数不足，只能抽取 ${remainingParticipants.length} 人，是否继续？`)) {
            return;
        }
    }

    if (isDrawing) {
        toggleDraw(); // 如果已经在手动抽奖，先停止
    }

    isDrawingAll = true;
    shouldPauseDrawAll = false;
    elements.drawAllBtn.innerHTML = '<i class="fa fa-pause mr-2"></i> 暂停抽奖';
    elements.drawBtn.disabled = true;

    let count = Math.min(remaining, remainingParticipants.length);
    let delay = 0;
    let speed = 50;
    let slowDownFactor = 1;
    let drawInterval = null;

    const startRolling = () => {
        isDrawing = true;
        shouldPauseDrawAll = false;

        audioElements.drawSound.currentTime = 0;
        audioElements.drawSound.loop = true;
        audioElements.drawSound.play();

        drawInterval = setInterval(() => {
            const randomIndex = Math.floor(Math.random() * remainingParticipants.length);
            elements.lotteryResult.textContent = remainingParticipants[randomIndex];

            if (Math.random() < 0.05 * slowDownFactor) {
                speed += 5;
                clearInterval(drawInterval);
                drawInterval = setInterval(() => {
                    const randomIndex = Math.floor(Math.random() * remainingParticipants.length);
                    elements.lotteryResult.textContent = remainingParticipants[randomIndex];
                }, speed);
                slowDownFactor += 0.1;
            }
        }, speed);

        setTimeout(() => {
            const slowDownInterval = setInterval(() => {
                if (speed > 200) {
                    clearInterval(slowDownInterval);
                }
            }, 500);
        }, 3000 + Math.random() * 2000);
    };

    const stopRollingAndShowWinner = (winner) => {
        clearInterval(drawInterval);
        isDrawing = false;

        audioElements.drawSound.pause();
        audioElements.drawSound.currentTime = 0;

        audioElements.winSound.currentTime = 0;
        audioElements.winSound.play();

        elements.lotteryResult.textContent = winner;
        elements.lotteryResult.classList.add('scale-up');

        elements.lotteryDecor.classList.remove('opacity-0');
        elements.lotteryDecor.classList.add('opacity-100');
        elements.lotteryContainer.classList.add('lottery-glow');

        setTimeout(() => {
            elements.lotteryResult.classList.remove('scale-up');
            elements.lotteryDecor.classList.add('opacity-0');
            elements.lotteryDecor.classList.remove('opacity-100');
            elements.lotteryContainer.classList.remove('lottery-glow');
        }, 2000);
    };

    const drawNext = () => {
        if (count <= 0 || shouldPauseDrawAll) { // 判断是否暂停
            // console.log('抽奖已暂停');
            clearInterval(drawInterval);
            clearTimeout(drawAllTimeout);
            isDrawing = false;
            isDrawingAll = false;

            elements.drawAllBtn.innerHTML = '<i class="fa fa-bolt mr-2"></i> 一键抽完';
            elements.drawBtn.disabled = false;
            return;
        }

        startRolling();

        setTimeout(() => {
            const randomIndex = Math.floor(Math.random() * remainingParticipants.length);
            const winner = remainingParticipants[randomIndex];

            if (!appState.winners[currentPrize.id]) {
                appState.winners[currentPrize.id] = [];
            }
            appState.winners[currentPrize.id].push(winner);
            remainingParticipants.splice(randomIndex, 1);

            storage.save('winners', appState.winners); // 及时保存中奖记录
            renderWinners(); // 更新中奖名单 UI

            stopRollingAndShowWinner(winner);

            count--;
            addHistoryEntry(`抽中 ${currentPrize.name}: ${winner}`);

            // 👇 新增：更新剩余名额
            const newWinnersCount = appState.winners[currentPrize.id].length;
            const newRemaining = currentPrize.count - newWinnersCount;
            elements.remainingCount.textContent = newRemaining;

            const prizeGroup = document.querySelector(`#winners-list-${currentPrize.id}`).parentElement;
            prizeGroup.classList.add('scale-up');
            setTimeout(() => {
                prizeGroup.classList.remove('scale-up');
            }, 300);

            if (count > 0 && !shouldPauseDrawAll) {
                delay = 800 + Math.random() * 400;
                drawAllTimeout = setTimeout(() => {
                    drawNext();
                }, delay);
            } else {
                storage.save('winners', appState.winners);
                renderWinners();
                selectPrize(currentPrize.id);
                audioElements.winSound.currentTime = 0;
                audioElements.winSound.play();

                isDrawingAll = false;
                shouldPauseDrawAll = false;
                elements.drawAllBtn.innerHTML = '<i class="fa fa-bolt mr-2"></i> 一键抽完';
                elements.drawBtn.disabled = false;
            }
        }, 3000 + Math.random() * 2000);
    };

    // 移除旧的监听器，避免重复绑定
    elements.drawAllBtn.removeEventListener('click', drawAll);
    elements.drawAllBtn.addEventListener('click', function handlePause() {
        shouldPauseDrawAll = true;
        elements.drawAllBtn.innerHTML = '<i class="fa fa-bolt mr-2"></i> 一键抽完';
        elements.drawAllBtn.removeEventListener('click', handlePause);
        elements.drawAllBtn.addEventListener('click', drawAll);
    });

    drawNext();
}

// 添加奖项
function addPrize() {
    const name = elements.newPrizeName.value.trim();
    const count = parseInt(elements.newPrizeCount.value, 10);

    if (!name) {
        alert('请输入奖项名称');
        return;
    }

    if (isNaN(count) || count <= 0) {
        alert('请输入有效的中奖名额');
        return;
    }

    const newPrize = {
        id: Date.now().toString(),
        name: name,
        count: count
    };

    appState.prizes.push(newPrize);
    storage.save('prizes', appState.prizes);

    elements.newPrizeName.value = '';
    elements.newPrizeCount.value = '';

    renderPrizeList();
    updatePrizeSelect();

    const prizeElements = document.querySelectorAll('.prize-item');
    if (prizeElements.length > 0) {
        prizeElements[prizeElements.length - 1].classList.add('scale-up');
        setTimeout(() => {
            prizeElements[prizeElements.length - 1].classList.remove('scale-up');
        }, 300);
    }
}

// 渲染奖项列表
function renderPrizeList() {
    elements.prizeList.innerHTML = '';
    if (appState.prizes.length === 0) {
        elements.emptyPrizes.classList.remove('hidden');
    } else {
        elements.emptyPrizes.classList.add('hidden');
        appState.prizes.forEach(prize => {
            const prizeItem = document.createElement('div');
            prizeItem.className = 'prize-item bg-dark/50 p-4 rounded-lg transition-all duration-300 hover:bg-dark/70';
            prizeItem.innerHTML = `
                <div class="flex justify-between items-center">
                    <div>
                        <h3 class="font-bold text-white">${prize.name}</h3>
                        <p class="text-sm text-gray-300">名额: ${prize.count}</p>
                    </div>
                    <button class="delete-prize-btn px-3 py-1 bg-danger/20 text-danger rounded hover:bg-danger/30 transition-colors">
                        <i class="fa fa-trash"></i>
                    </button>
                </div>
            `;
            const deleteBtn = prizeItem.querySelector('.delete-prize-btn');
            if (deleteBtn) {
                deleteBtn.addEventListener('click', () => {
                    if (confirm(`确定要删除奖项 "${prize.name}" 吗？`)) {
                        appState.prizes = appState.prizes.filter(p => p.id !== prize.id);
                        if (appState.winners[prize.id]) {
                            delete appState.winners[prize.id];
                        }
                        storage.save('prizes', appState.prizes);
                        storage.save('winners', appState.winners);
                        renderPrizeList();
                        updatePrizeSelect();
                        renderWinners();
                        selectPrize(null);
                    }
                });
            }

            elements.prizeList.appendChild(prizeItem);
        });
    }
}

// 更新奖项下拉框
function updatePrizeSelect() {
    const selectedValue = elements.prizeSelect.value;
    elements.prizeSelect.innerHTML = '<option value="">请选择奖项</option>';
    appState.prizes.forEach(prize => {
        const option = document.createElement('option');
        option.value = prize.id;
        option.textContent = `${prize.name} (${prize.count}名)`;
        if (prize.id === selectedValue) {
            option.selected = true;
        }
        elements.prizeSelect.appendChild(option);
    });
}

// 保存参与名单
function saveParticipants() {
    const input = elements.participants.value;
    if (!input.trim()) {
        alert('请输入至少一个参与者');
        return;
    }

    appState.participants = input.split('\n').map(name => name.trim()).filter(name => name.length > 0);
    storage.save('participants', appState.participants);
    alert('参与名单保存成功');
    updateDrawButtons();
}

// 处理BGM上传
function handleBgmUpload(event) {
    const file = event.target.files[0];
    if (!file) return;

    elements.bgmFilename.textContent = file.name;

    const reader = new FileReader();
    reader.onload = function (e) {
        const bgmId = Date.now().toString();
        const newBgm = {
            id: bgmId,
            name: file.name,
            data: e.target.result
        };
        appState.bgmFiles[bgmId] = newBgm;
        storage.save('bgmFiles', appState.bgmFiles);
        renderBgmList();
        updateBgmSelect();
        alert('音乐文件上传成功');
    };

    reader.onerror = function (e) {
        alert('读取文件失败');
    };

    reader.readAsArrayBuffer(file);
}

// 测试播放BGM
function testBgm() {
    const bgmId = elements.bgmSelect.value;
    if (!bgmId) {
        alert('请选择一个BGM');
        return;
    }

    const bgm = appState.bgmFiles[bgmId];
    if (!bgm) {
        alert('找不到所选BGM');
        return;
    }

    if (bgm.url) {
        elements.bgmPlayer.src = bgm.url; // 使用默认或上传保存的 URL
    } else if (bgm.data) {
        const blob = new Blob([new Uint8Array(bgm.data)], { type: 'audio/mp3' });
        const url = URL.createObjectURL(blob);
        elements.bgmPlayer.src = url;
    }

    elements.bgmPlayer.loop = true;
    elements.bgmPlayer.play().catch(error => {
        console.error('播放音频失败:', error);
        alert('无法自动播放音频，请手动点击播放按钮');
    });
}

// 播放BGM
function playBgm(bgm) {
    if (!bgm) return;

    if (bgm.url) {
        elements.bgmPlayer.src = bgm.url;
    } else if (bgm.data) {
        const blob = new Blob([new Uint8Array(bgm.data)], { type: 'audio/mp3' });
        const url = URL.createObjectURL(blob);
        elements.bgmPlayer.src = url;
    }

    elements.bgmPlayer.loop = true;
    elements.bgmPlayer.play().catch(error => {
        console.error('播放音频失败:', error);
    });
}

// 停止BGM
function stopBgm() {
    elements.bgmPlayer.pause();
    elements.bgmPlayer.currentTime = 0;
}

// 渲染BGM列表
function renderBgmList() {
    elements.bgmList.innerHTML = '';
    const bgmFiles = appState.bgmFiles;
    if (Object.keys(bgmFiles).length === 0) {
        elements.emptyBgm.classList.remove('hidden');
        return;
    }
    elements.emptyBgm.classList.add('hidden');
    for (const key in bgmFiles) {
        const bgm = bgmFiles[key];
        const bgmItem = document.createElement('div');
        bgmItem.className = 'bg-dark/50 p-3 rounded-lg flex justify-between items-center';
        bgmItem.innerHTML = `
            <span class="text-white">${bgm.name}</span>
            <button class="delete-bgm-btn text-danger hover:text-danger/80 transition-colors"><i class="fa fa-trash"></i></button>
        `;
        const deleteBtn = bgmItem.querySelector('.delete-bgm-btn');
        if (deleteBtn) {
            deleteBtn.addEventListener('click', () => {
                if (confirm(`确定要删除音乐 "${bgm.name}" 吗？`)) {
                    delete bgmFiles[key];
                    storage.save('bgmFiles', bgmFiles);
                    renderBgmList();
                    updateBgmSelect();
                }
            });
        }
        elements.bgmList.appendChild(bgmItem);
    }
}

// 更新BGM下拉框
function updateBgmSelect() {
    elements.bgmSelect.innerHTML = '<option value="">无音乐</option>';
    for (const key in appState.bgmFiles) {
        const option = document.createElement('option');
        option.value = key;
        option.textContent = appState.bgmFiles[key].name;
        elements.bgmSelect.appendChild(option);
    }
}

// 导出中奖名单
function exportWinners() {
    let output = '';
    for (const prizeId in appState.winners) {
        const prize = appState.prizes.find(p => p.id === prizeId);
        if (prize) {
            output += `${prize.name}(${prize.count}名):\n`;
            appState.winners[prizeId].forEach(w => output += ` - ${w}\n`);
            output += '\n';
        }
    }

    if (!output.trim()) {
        alert('暂无中奖记录');
        return;
    }

    storage.saveFile('中奖名单.txt', output);
}
// 渲染中奖名单 - 横向排布，放不下就换行
function renderWinners() {
    elements.winnersContainer.innerHTML = '';
    if (Object.keys(appState.winners).length === 0) {
        elements.emptyWinners.classList.remove('hidden');
        return;
    }
    elements.emptyWinners.classList.add('hidden');

    for (const prizeId in appState.winners) {
        const prize = appState.prizes.find(p => p.id === prizeId);
        if (!prize) continue;

        const prizeGroup = document.createElement('div');
        prizeGroup.className = 'mb-6';

        prizeGroup.innerHTML = `            <h3 class="font-bold font-display text-lg mb-3 text-primary">${prize.name} (${prize.count}名)</h3>
            <div class="flex flex-wrap gap-2" id="winners-list-${prizeId}"></div>
        `;

        const winnersList = prizeGroup.querySelector(`#winners-list-${prizeId}`);
        const winners = appState.winners[prizeId];

        winners.forEach(winner => {
            const winnerItem = document.createElement('div');
            winnerItem.className = 'flex items-center bg-white/5 px-3 py-2 rounded-lg min-w-max';
            winnerItem.innerHTML = `<i class="fa fa-trophy text-warning mr-2"></i><span>${winner}</span>`;
            winnersList.appendChild(winnerItem);
        });

        elements.winnersContainer.appendChild(prizeGroup);
    }
}
// 初始化默认 BGM（从 audio/ 目录下预设音乐）
function initializeDefaultBGM() {
    const defaultBGMs = [
        { name: '背景音乐一', src: 'audio/background-music-1.mp3' },
        { name: '背景音乐二', src: 'audio/background-music-2.mp3' },
        { name: '背景音乐三', src: 'audio/background-music-3.mp3' }
    ];

    // 始终添加默认音乐，不管是否已上传自定义音乐
    const existingBgmFiles = { ...appState.bgmFiles }; // 保留已有音乐

    defaultBGMs.forEach((bgm, index) => {
        const bgmId = `default-${index}`;
        existingBgmFiles[bgmId] = {
            id: bgmId,
            name: bgm.name,
            url: bgm.src
        };
    });

    appState.bgmFiles = existingBgmFiles;
    storage.save('bgmFiles', appState.bgmFiles);
    renderBgmList();
    updateBgmSelect();
}
// 页面加载初始化
document.addEventListener('DOMContentLoaded', () => {
    const storedBgmFiles = JSON.parse(localStorage.getItem('bgmFiles') || '{}');
    const bgmFilesWithUrl = {};
    for (const key in storedBgmFiles) {
        const bgm = storedBgmFiles[key];
        bgmFilesWithUrl[key] = {
            ...bgm,
            url: ''
        };
    }

    appState.bgmFiles = bgmFilesWithUrl;
    renderBgmList();
    updateBgmSelect();

    // 初始化默认背景音乐（可选）
    initializeDefaultBGM();
});

// 确保 DOM 加载后再初始化
document.addEventListener('DOMContentLoaded', init);




